<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import { getMenu, hideMenu, getPropsMapping } from './_dropdown.js';
const root = ref(null);

const props = defineProps({
    trigger: {
        type: String,
        default: 'click'
    },
    props: {
        type: Object,
        default: () => { }
    },
    menus: {
        type: Array,
        default: () => []
    }
});


const menu = ref(null)
let propsMapping = getPropsMapping(props.props)
menu.value = getMenu({ children: props.menus }, propsMapping)

watch(
    () => props.menus,
    (newMenus) => {
        menu.value = getMenu({ children: newMenus }, propsMapping)
    },
    { immediate: true, deep: true }
);



let clickOutsideHandler = null;
onMounted(() => {
    clickOutsideHandler = (event) => { hideMenu(root.value, menu.value, event) };
    document.addEventListener('click', clickOutsideHandler);
});
onBeforeUnmount(() => {
    document.removeEventListener('click', clickOutsideHandler);
})
</script>



<template>
    <div ref="root">
        <span :ref="(el) => menu.ref = el" v-on="menu.event">
            <slot></slot>
        </span>
        <x-menu :menu="menu"></x-menu>
    </div>
</template>

<style>
.dropdown {
    position: fixed;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
    background: #fff;
    border-radius: 4px;
    padding: 8px 0;
    user-select: none;
    box-sizing: border-box;
    border-color: 1px solid rgba(67, 64, 64, 0.175);
    cursor: default;
}

.dropdown-body {
    display: block;
}

.dropdown-item {
    color: #606266;
    display: flex;
    align-items: center;
    padding: 0.2rem 1rem;
    margin: 0;
    font-size: 0.857rem;
    outline: 0;
    align-items: center;
    transition: 0.2s;
    box-sizing: border-box;
    list-style: none;
    border-bottom: 1px solid #00000000;
}


.dropdown-icon {
    flex-shrink: 0;
    margin-right: 8px;
    padding: 0.2rem 0.2rem;
}

.dropdown-label {
    white-space: nowrap;
    margin-right: 16px;
}

.dropdown-content {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-right: 16px;
}

.dropdown-suffix {
    flex-shrink: 0;
    margin-left: 8px;

}

.dropdown-divided {
    height: 0;
    margin: 0.2rem 0;
    overflow: hidden;
    border-top: 1px solid rgba(0, 0, 0, 0.175);
    opacity: 1;

}

.dropdown-available {
    color: #606266;
    cursor: pointer;
}

.dropdown-disabled {
    color: #c0c4cc;
    cursor: not-allowed;
}

.dropdown-item:hover,
.dropdown-active {
    background: #f8f9fa;
}
</style>